#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <Shinygami/datafile.hpp>
#include <QMessageBox>
#include <QSettings>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    QIcon favicon("icons/favicon.png");

    ui->setupUi(this);
    ui->projectView->hide();
    setWindowIcon(favicon);
    setWindowTitle("Celestia's Workshop - The proud Shinygami Game Editor");
    connect(ui->projectsView, SIGNAL(CreateNewProject(QString,QString)), this, SLOT(NewProject(QString,QString)));
    connect(ui->projectsView, SIGNAL(LoadProject(QString)), this, SLOT(LoadProject(QString)));
    readSettings();
}

MainWindow::~MainWindow()
{
    writeSettings();
    delete ui;
}

void MainWindow::NewProject(QString name, QString folder)
{
    Project newProject(name, folder);

    if (newProject.Save())
    {
        ui->projectView->LoadProject(newProject);
        ui->projectsView->hide();
        ui->projectView->show();
        this->setWindowTitle("Celestia's Workshop - " + name);
    }
}

void MainWindow::LoadProject(QString filepath)
{
    Project project(filepath);

    if (project._loadedWithSuccess)
    {
        ui->projectView->LoadProject(project);
        ui->projectsView->hide();
        ui->projectView->show();
        setWindowTitle("Celestia's Workshop - " + project.Name());
    }
}

void MainWindow::writeSettings()
{
    QSettings settings;

    settings.beginGroup("MainWindow");
    settings.setValue("size", size());
    settings.setValue("pos", pos());
    settings.endGroup();
}

void MainWindow::readSettings()
{
    QSettings settings;

    settings.beginGroup("MainWindow");
    resize(settings.value("size", QSize(400, 400)).toSize());
    move(settings.value("pos", QPoint(50, 50)).toPoint());
    settings.endGroup();
}
